const config = require('../../core/config')
const SecCheck = require('../../core/SecCheck')
const app = getApp();
const PAGE_SIZE = config.PageSize;
Page({
  data: {
    bottom: 0,
    hasUserInfo: false,
    vis: false,
    postList: [],
    showbar: true,
    postid: '',
    oncomment: false,
    replyuserInfo: null,
    replycontent: ''
  },
  taInput(e) {
    this.setData({
      replycontent: e.detail.value
    })
  },
  handleSend() {
    var that = this;
    //获取用户信息
    let userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || ''
    let openid = app.globalData.openid || wx.getStorageSync('openid') || ''
    if (openid == '' || userInfo == '') {
      this.setData({
        errMsg: '缺少用户信息'
      })
      return
    }
    SecCheck.msgSecCheck(this.data.replycontent).then(ans => {
      console.log(ans)
      if (ans.result.code == 200) {
        wx.cloud.callFunction({
          name: 'comment',
          data: {
            action: 'add',
            data: {
              postid: this.data.postid,
              userInfo,
              replyuserInfo: this.data.replyuserInfo,
              openid,
              replycontent: this.data.replycontent
            }
          },
          success: r => {
            var date = this.dateFormat("YYYY-mm-dd HH:MM", new Date())
            wx.cloud.callFunction({
                name: 'addScore',
                data: {
                  openid: wx.getStorageSync('openid'),
                  score: 5
                }
              })
              .then(res => {
                console.log(res)
                wx.showToast({
                  icon: 'none',
                  title: '评论成功，积分+5',
                })
              })
            wx.cloud.callFunction({
              name: 'sentDiscussCommentMessage',
              data: {
                openid: this.data.posterId,
                id: this.data.postid,
                content: this.data.replycontent,
                time: date
              }
            })
            console.log(r)
            /**
             * 全部组件进行刷新
             */
            let acmp = that.selectAllComponents('.card')
            // console.log(acmp)
            acmp.forEach(function (ele, index) {
              ele.flushComment(that.data.postid)
            })
            that.setData({
              postid: ''
            })

          }
        })
      } else {
        this.setData({
          errMsg: ans.result.msg,
          postid: ''
        })
      }
    })
  },
  deletepost(e) {
    let docid = e.detail
    let tarr = this.data.postList
    let deleteIndex = tarr.findIndex(item => item._id === docid);
    tarr.splice(deleteIndex, 1)
    console.log(tarr)
    this.setData({
      postList: tarr
    })
  },
  posterId(e) {
    console.log(e.currentTarget.dataset.posterid.openid)
    this.setData({
      posterId: e.currentTarget.dataset.posterid.openid
    })
  },
  baraction(e) {
    console.log(e.detail)
    this.setData({
      postid: e.detail.postid,
      replyuserInfo: e.detail.replyuserInfo,
      oncomment: true
    })
  },
  hideShowBar() {
    var that = this;
    // let markcard = this.selectComponent('#wxcard')
    // markcard.closeActionBar();
    let acmp = this.selectAllComponents('.card')
    // console.log(acmp)
    acmp.forEach(function (ele, index) {
      ele.closeActionBar();
    })
    if (this.data.oncomment) {
      this.setData({
        oncomment: false
      })
      return
    }
    this.setData({
      postid: ''
    })
    // markcard.closeActionBar();
  },
  reqPostData() {
    let postList = this.data.postList
    let len = postList.length
    this.setData({
      vis: true
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'query',
        size: PAGE_SIZE,
        step: len,
        data: {}
      },
      success: r => {
        wx.stopPullDownRefresh({
          success: (res) => {},
        })
        console.log(r.result.data[0])
        this.setData({
          vis: false,
          postList: postList.concat(r.result.data)
        })
      },
      fail: r => {
        console.log(r)

      },
      complete: res => {
        this.setData({
          vis: false
        })
      }
    })
  },
  showEditPage() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/post/post',
      })
    } else {
      wx.navigateTo({
        url: '/pages/user/login/login',
      })
    }
  },

  onLoad: function (options) {
    let app = getApp();
    console.log(app.globalData)
    this.setData({
      envVersion: __wxConfig.envVersion
    })
    // this.setData({
    //   envVersion: 'release'
    // })
    this.setData({ //请求讨论圈信息
      postList: []
    }, () => {
      this.reqPostData()
    })
  },

  onShow: function () {
    if (wx.getStorageSync("userInfo")) {
      this.setData({
        userInfo: wx.getStorageSync("userInfo"),
        hasUserInfo: true
      })
    }
  },

  onPullDownRefresh: function () { //监听用户下拉动作
    this.setData({
      postList: []
    }, () => {
      this.reqPostData();
    })
  },

  onReachBottom: function () {
    this.reqPostData() //请求讨论圈信息
  },
  onShareAppMessage: function (res) {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = `/${currentPage.route}`
    return {
      title: 'TLradio - 讨论圈',
      path: url,
      //imageUrl: '../../images/share1.png'
    }
  },
  dateFormat(fmt, date) {
    let ret
    const opt = {
      "Y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    }
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt)
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      }
    }
    return fmt
  }
})